package com.meisupic.copyright.service.impl;

import com.meisupic.copyright.domain.bo.SysUser;
import com.meisupic.copyright.domain.po.RealNameAuth;
import com.meisupic.copyright.domain.po.Users;
import com.meisupic.copyright.repo.UsersRepo;
import com.meisupic.copyright.service.IRealNameAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @Author lanjian
 * @Date 2018/3/11 下午9:53
 */
@Service("userCaidDetailsService")
public class UserCaidServiceImpl implements UserDetailsService {


  @Autowired
  private IRealNameAuthService realNameAuthService;

  @Autowired
  private UsersRepo usersRepo;

  /**
   * Locates the user based on the username. In the actual implementation, the search may possibly
   * be case sensitive, or case insensitive depending on how the implementation instance is
   * configured. In this case, the <code>UserDetails</code> object that comes back may have a
   * username that is of a different case than what was actually requested..
   *
   * @param username the username identifying the user whose data is required.
   * @return a fully populated user record (never <code>null</code>)
   * @throws UsernameNotFoundException if the user could not be found or the user has no
   * GrantedAuthority
   */
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Long userId = Long.valueOf(username);
    RealNameAuth realNameAuth = realNameAuthService.findByUserId(userId);
    if(realNameAuth==null){
      throw new UsernameNotFoundException("用户未找到");
    }
    Users users = usersRepo.findOne(userId);
    if (users == null) {
      throw new UsernameNotFoundException("用户未找到");
    }
    SysUser sysUser = new SysUser();
    sysUser.setId(userId);
    sysUser.setPassword(realNameAuth.getAccountId());
    sysUser.setUserName(users.getUserName());
    return sysUser;
  }
}
